package com.ph.clouds.tracker.network;

import android.os.Handler;
import android.os.Looper;


import com.ph.clouds.tracker.util.TrackerLog;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @Author yushuangjiang
 * @Time 2021/8/3 15:16
 * @Description：
 */
public class JsonHttpListener implements IHttpListener {

   private IDataListener dataListener;

   public JsonHttpListener(IDataListener dataListener) {
       this.dataListener = dataListener;
   }

   //用于切换线程
   Handler handler = new Handler(Looper.getMainLooper());

   @Override
   public void onSuccess(InputStream inputStream) {
       //获取响应结果，把byte数据转换成String数据
       String content = getContent(inputStream);
       TrackerLog.i("Tracker-Response:", content);
       //将json字符串转换成对象
       //final M response = JSON.parseObject(content, responseClass);
       //把结果传送到调用层
       handler.post(() -> {
           if (dataListener != null) {
               dataListener.onSuccess(content);
           }
       });

   }

   @Override
   public void onFailure() {
       handler.post(() -> {
           if (dataListener != null) {
               dataListener.onFailure();
           }
       });

   }

   /**
    * 将流转换成字符串
    */
   private String getContent(InputStream inputStream) {
       BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
       StringBuilder sb = new StringBuilder();
       String line = null;
       try {
           while ((line = reader.readLine()) != null) {
               sb.append(line + "\n");
           }
       } catch (IOException e) {
           e.printStackTrace();
       } finally {
           try {
               inputStream.close();
               reader.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
       return sb.toString();
   }

}
